package com.fulihui.wgj.admin.api.wx48;

import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.result.web.PageView;
import com.fulihui.common.result.web.Result;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.weixinsdk.model.Article;
import com.fulihui.weixinsdk.model.NewsMessage;
import com.fulihui.weixinsdk.request.material.UploadImgRequest;
import com.fulihui.weixinsdk.result.material.UploadImgResult;
import com.fulihui.wgj.admin.api.base.BaseController;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsCalcRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsCancelRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsLogPageRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsQueryRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSaveModel;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSaveRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSendPreRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSendRequest;
import com.fulihui.wgj.admin.api.wx48.vo.Wx48NewsInfoVO;
import com.fulihui.wgj.admin.api.wx48.vo.Wx48NewsLogVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.Wx48NewsServiceClient;
import com.fulihui.wgj.admin.integration.WxPlatformClient;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsInfoSaveRequest;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.fulihui.common.error.Errors.Commons.REQUEST_PARAMETER_ERROR;
import static com.fulihui.common.error.Errors.WxSystemConfigError.GET_TOKEN_FAILED;

/**
 * @author: Levon
 * @date: 2018-07-19 14:04
 */
@RestController
@RequestMapping("/wx48")
@Api(tags = "微信48小时消息相关接口")
public class Wx48ManageController extends BaseController {

    @Autowired
    private WeixinSDK weixinSDK;
    @Autowired
    private WxPlatformClient wxPlatformClient;
    @Autowired
    private Wx48NewsServiceClient wx48NewsServiceClient;
    @Autowired
    private AdminProperties adminProperties;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ApiOperation("保存48小时消息")
    public Result<Long> save48News(HttpServletRequest servletRequest, @RequestBody Wx48NewsSaveRequest request) {

        if (CollectionUtils.isEmpty(request.getNews())) {
            return JsonResultBuilder.fail(REQUEST_PARAMETER_ERROR.getErrcode(), REQUEST_PARAMETER_ERROR.getErrmsg());
        }

        String accessToken = wxPlatformClient.queryTokenFromRedis(getAppid(servletRequest));
        if (StringUtils.isBlank(accessToken)) {
            return JsonResultBuilder.fail(GET_TOKEN_FAILED.getErrcode(), GET_TOKEN_FAILED.getErrmsg());
        }

        NewsMessage newsMessage = new NewsMessage();

        List<Article> articles = Lists.newArrayList();

        for (Wx48NewsSaveModel model : request.getNews()) {

            String imgUrl = model.getImgUrl();
            String[] split = imgUrl.split("img-proxy\\?");
            String url = model.getUrl();
            String title = model.getTitle();
            articles.add(new Article(title, "", url, split[1]));
        }

        NewsMessage.News news = new NewsMessage.News();
        news.setArticles(articles);
        newsMessage.setNews(news);

        String title1 = servletRequest.getParameter("title1");
        Wx48NewsInfoSaveRequest saveRequest = new Wx48NewsInfoSaveRequest();
        saveRequest.setId(request.getId());
        saveRequest.setAppId(getAppid(servletRequest));
        saveRequest.setTitle(title1);
        saveRequest.setUseType(request.getUseType());
        saveRequest.setXmlContent(JSON.toJSONString(newsMessage));
        return wx48NewsServiceClient.saveNews(saveRequest);
    }


    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation("上传图文中图片素材")
    public Result<String> uploadImage(@RequestParam("imgFile") MultipartFile multfile, HttpServletRequest servletRequest) {
        String fileName = multfile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        String appid = servletRequest.getParameter("appid");
        File file = null;
        try {
            file = File.createTempFile(UUID.randomUUID().toString(), prefix);
            multfile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String accessToken = wxPlatformClient.queryTokenFromRedis(appid);
        if (StringUtils.isBlank(accessToken)) {
            return JsonResultBuilder.fail(GET_TOKEN_FAILED.getErrcode(), GET_TOKEN_FAILED.getErrmsg());
        }

        String imageUrl = uploadImg(file, accessToken);
        if (StringUtils.isNotBlank(imageUrl)) {
            imageUrl = adminProperties.getImgproxy() + imageUrl;
        }

        return JsonResultBuilder.succ(imageUrl);
    }

    @PostMapping("/queryPage")
    @ApiOperation("获取48小时图文素材列表")
    public Result<PageView<Wx48NewsInfoVO>> queryNewsList(@RequestBody @Valid Wx48NewsQueryRequest request, BindingResult validResult, HttpServletRequest servletRequest) {
        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }
        request.setAppId(getAppid(servletRequest));
        PageView<Wx48NewsInfoVO> pageView = wx48NewsServiceClient.queryPage(request);
        return JsonResultBuilder.succ(pageView);
    }

    @PostMapping("/querySpecial")
    @ApiOperation("获取特定48小时图文素材")
    public Result<Wx48NewsInfoVO> querySpecial(HttpServletRequest servletRequest) {
        Wx48NewsInfoVO wx48NewsInfo = wx48NewsServiceClient.querySpecificReply(getAppid(servletRequest));
        return JsonResultBuilder.succ(wx48NewsInfo);
    }

    @RequestMapping(value = "/calc", method = RequestMethod.POST)
    @ApiOperation("计算人群数量")
    public Result<String> calc(@RequestBody @Valid Wx48NewsCalcRequest request, BindingResult validResult, HttpServletRequest servletRequest) {
        request.setAppId(getAppid(servletRequest));
        Result<String> result = wx48NewsServiceClient.sendSalc(request);
        return result;
    }

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ApiOperation("发送消息")
    public Result<Boolean> send(@RequestBody @Valid Wx48NewsSendRequest request, BindingResult validResult, HttpServletRequest servletRequest) {
        request.setAppId(getAppid(servletRequest));
        Result<Boolean> result = wx48NewsServiceClient.send(request);
        return result;
    }

    @PostMapping("/log/queryPage")
    @ApiOperation("分页查询48小时图文消息记录")
    public Result<PageView<Wx48NewsLogVO>> queryNewsLogList(@RequestBody @Valid Wx48NewsLogPageRequest request, BindingResult validResult,
                                                            HttpServletRequest servletRequest) {
        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }
        request.setAppId(getAppid(servletRequest));
        PageView<Wx48NewsLogVO> pageView = wx48NewsServiceClient.queryNewsLogPage(request);
        return JsonResultBuilder.succ(pageView);
    }

    @RequestMapping(value = "/sendPre", method = RequestMethod.POST)
    @ApiOperation("发送到手机预览")
    public Result<Boolean> sendPre(@RequestBody @Valid Wx48NewsSendPreRequest request,
                                   HttpServletRequest servletRequest, BindingResult validResult) {
        request.setAppId(getAppid(servletRequest));
        Result<Boolean> result = wx48NewsServiceClient.sendPre(request);
        return result;
    }

    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ApiOperation("取消发送")
    public Result<Boolean> cancel(@RequestBody @Valid Wx48NewsCancelRequest request, BindingResult validResult,
                                  HttpServletRequest servletRequest) {
        Result<Boolean> result = wx48NewsServiceClient.cancel(request);
        return result;
    }

    /**
     * 微信上传图片
     *
     * @param file
     * @param accessToken
     * @return
     */
    private String uploadImg(File file, String accessToken) {
        UploadImgRequest uploadImgRequest = new UploadImgRequest();
        uploadImgRequest.setAccess_token(accessToken);
        uploadImgRequest.setMedia(file);
        UploadImgResult uploadImgResult = weixinSDK.invokeService(uploadImgRequest);
        if (uploadImgResult.isSuccess()) {
            return uploadImgResult.getUrl();
        }
        return null;
    }
}
